import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# 加载数据
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
df = pd.read_csv(url, header=None,
                 names=['sepal_len', 'sepal_wid', 'petal_len', 'petal_wid', 'species'])

# 创建多面板图
fig = plt.figure(figsize=(16, 12))

# 1. 整体分布
ax1 = fig.add_subplot(221)
ax1.boxplot([df[col] for col in df.columns[:-1]], labels=df.columns[:-1])
ax1.set_title('特征值分布')

# 2. 种类对比
ax2 = fig.add_subplot(222)
colors = {'Iris-setosa': 'red', 'Iris-versicolor': 'green', 'Iris-virginica': 'blue'}
for species, group in df.groupby('species'):
    ax2.scatter(group['sepal_len'], group['petal_len'], color=colors[species],
                label=species, alpha=0.7)
ax2.set_xlabel('萼片长度')
ax2.set_ylabel('花瓣长度')
ax2.legend()

# 3. 3D散点图
ax3 = fig.add_subplot(223, projection='3d')
for species, group in df.groupby('species'):
    ax3.scatter(group['sepal_len'], group['sepal_wid'], group['petal_len'],
                color=colors[species], label=species, s=50)
ax3.set_xlabel('萼片长度')
ax3.set_ylabel('萼片宽度')
ax3.set_zlabel('花瓣长度')
ax3.view_init(30, 45)  # 设置视角

# 4. 关系矩阵
from matplotlib.colors import ListedColormap
ax4 = fig.add_subplot(224)
species_map = {sp: i for i, sp in enumerate(df['species'].unique())}
colors = [colors[sp] for sp in df['species']]
ax4.scatter(df['petal_wid'], df['sepal_wid'], c=df['sepal_len'],
           s=df['petal_len']*20, alpha=0.7, cmap='viridis')
plt.colorbar(ax4.collections[0], label='萼片长度')

plt.suptitle('鸢尾花数据集多维可视化', fontsize=20)
plt.tight_layout(rect=[0, 0, 1, 0.96])  # 为总标题留空间
plt.savefig('iris_analysis.png', dpi=150)
plt.show()